package com.app.couponsharelife.ui.main.login

import android.content.Intent
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.NewBindPhoneBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.FinishActivityManager
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.ui.main.login.forgetpwd.NewForgetPswActivity
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.ToastUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_phonelogin.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit

/**
 *Created by xct on 2019/1/3
 *Description:手机号登录界面
 */
class PhoneLoginActivity:BaseActivity(),View.OnClickListener {
    private var userId=""
    private var userName=""
    private var unionId=""
    private var headPrice=""
    private var sex="1"
    private var city=""
    private var province=""
    private var isvisible=false
    private var disposable: Disposable? = null
    private val handler=MyHandler(this)
    override val viewLayoutId: Int
        get() = R.layout.activity_phonelogin

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        setEdit()
        phonelogin_llweixinlogin.setOnClickListener(this)
        phonelogin_llcolse.setOnClickListener(this)
        phonelogin_lleye.setOnClickListener(this)
        phonelogin_llempty.setOnClickListener(this)
        phonelogin_textwjmm.setOnClickListener(this)
        phonelogin_textlogin.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.phonelogin_llcolse->{
                hideSoftInput(this)
                finish()
            }
            R.id.phonelogin_llweixinlogin->{
                hideSoftInput(this)
                getWxUser()
            }
            R.id.phonelogin_lleye->{
                if (phonelogin_editpsw.transformationMethod === HideReturnsTransformationMethod.getInstance()) {
                    //显示密文
                    phonelogin_editpsw.transformationMethod = PasswordTransformationMethod.getInstance()
                    Glide.with(this).asBitmap().load(R.drawable.ic_edit_text_close_eye).into(phonelogin_psweye)
                } else {
                    //显示明文
                    phonelogin_editpsw.transformationMethod = HideReturnsTransformationMethod.getInstance()
                    Glide.with(this).asBitmap().load(R.drawable.ic_edit_text_open_eye).into(phonelogin_psweye)
                }
                //保证每次切换明文密文后光标都在最后面，默认是会切换到最前端
                phonelogin_editpsw.setSelection(phonelogin_editpsw.text.length)
            }
            R.id.phonelogin_llempty->{
                phonelogin_editpsw.setText("")
            }
            R.id.phonelogin_textwjmm->{
                startActivity(Intent(this,NewForgetPswActivity::class.java))
            }
            R.id.phonelogin_textlogin->{
                val phone=phonelogin_editphone.text.toString().trim()
                val psw=phonelogin_editpsw.text.toString().trim()
                if (phone.isEmpty()){
                    showToastMsg("请输入手机号码")
                    return
                }
                if (psw.isEmpty()){
                    showToastMsg("请输入密码")
                    return
                }
                if (phone.length<11){
                    showToastMsg("请输入正确的手机号码")
                    return
                }
                if (!AppUtils.isMobile(phone)){
                    showToastMsg("请输入正确的手机号码")
                    return
                }
                pswLogin(phone,psw)
            }
        }
    }
    private fun setEdit(){
        phonelogin_editpsw.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable) {
                if (s.isNotEmpty()){
                    phonelogin_llempty.visibility=View.VISIBLE
                    phonelogin_lleye.visibility=View.VISIBLE
                    if (phonelogin_editphone.text.toString().trim().isNotEmpty()){
                        phonelogin_textlogin.setBackgroundResource(R.drawable.shape_red_ff0_ff4)
                    }
                }else{
                    phonelogin_llempty.visibility=View.INVISIBLE
                    phonelogin_lleye.visibility=View.INVISIBLE
                    phonelogin_textlogin.setBackgroundResource(R.drawable.shape_gray_cc20)
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
        phonelogin_editphone.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable) {
                if (s.isNotEmpty()){
                    if (phonelogin_editpsw.text.toString().trim().isNotEmpty()){
                        phonelogin_textlogin.setBackgroundResource(R.drawable.shape_red_ff0_ff4)
                    }
                }else{
                    phonelogin_textlogin.setBackgroundResource(R.drawable.shape_gray_cc20)
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
    }
    private fun getWxUser(){
        val wechat= ShareSDK.getPlatform(Wechat.NAME)
        wechat.removeAccount(true)
        wechat!!.platformActionListener=object : PlatformActionListener {
            override fun onComplete(p0: Platform, p1: Int, p2: HashMap<String, Any>) {
                //Log.e("eeee","---->"+p0.db.userId+"---"+p0.db["unionid"]+"---"+p0.db.userName+"---"+p0.db.userIcon)
                //wxLogin(p0.db.userId,p0.db["unionid"],p0.db.userName,p0.db.userIcon)
                isvisible=false
                userId=p0.db.userId?:""
                unionId=p0.db["unionid"]?:""
                userName=p0.db.userName?:""
                headPrice=p0.db.userIcon?:""
                sex=p0.db["sex"]?:""
                city=p0.db["city"]?:""
                province=p0.db["province"]?:""
                val msg=Message()
                msg.what=0
                handler.sendMessage(msg)
            }

            override fun onCancel(p0: Platform?, p1: Int) {
                isvisible=false
            }

            override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                //showToastMsg("登录失败")
                isvisible=false
            }
        }
        wechat.showUser(null)
        isvisible=true
    }
    private fun wxLogin(openId:String,unionId:String,nickName:String,headPrice:String){
        val map = HashMap<String, String>()
        map["openId"] = openId
        map["unionId"] = unionId
        map["nickName"] = nickName
        map["headPrice"] = headPrice
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        //mViewModel?.freshWxLogin(map,true)
        RetrofitWorker.retrofitWorker.wxLogin(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<NewBindPhoneBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<NewBindPhoneBean>) {
                        dismissProgressDialog()
                        if (it.code == 200 && it.data!= null) {
                            showToastMsg("登录成功")
                            AppUtils.setString(Contacts.USER_MOBILE, it.data!!.mobile!!)
                            AppUtils.setString(Contacts.USERID, it.data!!.id!!)
                            AppUtils.setString(Contacts.ADZONE_ID, it.data!!.relation_id?:"")
                            AppUtils.setString(Contacts.INVITATION_CODE, it.data!!.requestcode?:"")
                            AppUtils.setString(Contacts.COMMISSION_RATIO, it.data!!.commissionRatio?:"")
                            FinishActivityManager.getInstance().finishAllActivity()
                            startActivity(Intent(this@PhoneLoginActivity, MainActivity::class.java))
                        } else {
                            showToastMsg("请求失败")
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){
                                if (userId.isNotEmpty()){
                                    val intent=Intent(this@PhoneLoginActivity,UserIdentitySelect::class.java)
                                    intent.putExtra("UserId",userId)
                                    intent.putExtra("UserName",userName)
                                    intent.putExtra("UnionId",unionId)
                                    intent.putExtra("HeadPrice",headPrice)
                                    intent.putExtra("Sex",sex)
                                    intent.putExtra("City",city)
                                    intent.putExtra("Province",province)
                                    startActivity(intent)
                                }else{
                                    showToastMsg("授权失败,请稍后重试")
                                }
                            }else{
                                showToastMsg(e.msg)
                            }
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun pswLogin(phone:String,psw:String){
        showProgressDialog("请稍后...")
        val map = HashMap<String, String>()
        map["mobile"] = phone
        map["password"] = psw
        val s1 = System.currentTimeMillis().toString()
        val s2 = AppUtils.getMapString(map)
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.newPwdLogin(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<NewBindPhoneBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<NewBindPhoneBean>) {
                        dismissProgressDialog()
                        if (it.code == 200 && it.data!= null) {
                            showToastMsg("登录成功")
                            AppUtils.setString(Contacts.USER_MOBILE, it.data!!.mobile!!)
                            AppUtils.setString(Contacts.USERID, it.data!!.id!!)
                            AppUtils.setString(Contacts.ADZONE_ID, it.data!!.relation_id?:"")
                            AppUtils.setString(Contacts.USER_GRADE_ID, it.data!!.sellerlevel.toString())
                            AppUtils.setString(Contacts.COMMISSION_RATIO, it.data!!.commissionRatio?:"")
                            FinishActivityManager.getInstance().finishAllActivity()
                            startActivity(Intent(this@PhoneLoginActivity, MainActivity::class.java))
                        } else {
                            showToastMsg("请求失败")
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            ToastUtil.getInstance().showToast(e.msg)
                        }
                    }

                })
    }
    override fun onResume() {
        super.onResume()
        if (isvisible){
            showProgressDialog("请稍后...")
        }
        if (disposable == null)
            disposable = Observable.interval(0, 2, TimeUnit.SECONDS)//10s 倒计时
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ aLong -> if (aLong != 0L) dismissProgressDialog() }) { dismissProgressDialog() }
    }
    override fun onDestroy() {
        super.onDestroy()
        disposable?.dispose()
        disposable=null
        AppUtils.destroyImmersionBar(this)
    }
    private class MyHandler(activity: PhoneLoginActivity) : Handler() {
        private val mActivity: WeakReference<PhoneLoginActivity> = WeakReference<PhoneLoginActivity>(activity)
        private var activity:PhoneLoginActivity?=null

        override fun handleMessage(msg: Message) {
            if (activity== null) {
                activity=mActivity.get()
            }
            when (msg.what) {
                0 -> {
                    activity!!.wxLogin(activity!!.userId,activity!!.unionId,activity!!.userName,activity!!.headPrice)
                }
                else -> {

                }
            }
        }
    }
}